package com.ggs.rg.ybjb.adminmodule.util;


import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClassName:ImageUtil
 * Package:com.ggs.rg.ybjb.adminmodule.util
 * Description:
 * 对从数据拿到的公告数据的image字段进行加工,给前端返回一个该获取图片的网址
 *
 * @Date:2021/10/31 11:18
 * @Author:cxw
 */
public class ImageUtil {

    /**
     * 返回一个获取指定图片的地址
     *
     * @param image
     * @return
     */
    public static String getImageAddr(String image, String port) {
//        try {
//            return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port + "/image/" + image;
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        }
//        return null;
        return "http://1.12.226.79" + ":" + port + "/image/" + image;
//        return "http://172.20.243.30" + ":" + port + "/image/" + image;
    }

    /**
     * 重置文件名
     *
     * @param multipartFile 多媒体对象(文件)
     * @return
     */
    public static String getNewFileName(MultipartFile multipartFile) {
        //获取文件后缀
        String contentType = multipartFile.getContentType();
        String[] suffix = contentType.split("/");
        //重新生成图片名
        String newName = System.currentTimeMillis() + "." + suffix[1];
        return newName;
    }

    /**
     * 将前端传过来的图片保存到服务器
     *
     * @param multipartFile 前端传过来的文件
     * @return 保存到服务器的文件名
     * @throws IOException
     */
    public static void saveFile(String fileName, MultipartFile multipartFile) throws IOException {
        //获取服务器根路径
        String path = ClassUtils.getDefaultClassLoader().getResource("static/image").getPath();
        File file = new File(path, fileName);
        //保存图片到服务器
        multipartFile.transferTo(file);
    }

    public static void deleteFile(String fileName) throws IOException {
        String path = ClassUtils.getDefaultClassLoader().getResource("static/image").getPath();
        String filePath = path + "/" + fileName;
        File file = new File(filePath);
        //如果图片存在则删除
        if (file.exists()) {
            boolean deleResult = file.delete();
            if (deleResult)
                System.out.println("删除原图片成功");
            else
                System.out.println("删除原图片失败");
        }
    }

    public static String image2Base64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return ImageUtil.encodeImage(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

    /**
     * 图片转字符串
     *
     * @param image
     * @return
     */
    public static String encodeImage(byte[] image) {
        BASE64Encoder decoder = new BASE64Encoder();
        return replaceEnter(decoder.encode(image));
    }

    public static String replaceEnter(String str) {
        String reg = "[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    public static void base64ToImage(String path, String base64) {
        File file = null;
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file = new File(path);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
